/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.transas.zorlog.data.log;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

/**
 *
 * @author amalikov
 */
public class BinsPacketReader extends PacketReader {
	public BinsPacketReader(InputStream in) {
		super(in);
	}
	
	@Override
	public ByteBuffer getPacket() throws IOException {
		while (true) {
			in.mark(65536);		// remember current position
			
			byte[] t = new byte[6];
			if (in.read(t) != t.length)
				return null;	// end of stream
		
			ByteBuffer bb = ByteBuffer.wrap(t).order(ByteOrder.LITTLE_ENDIAN);
			int head = bb.getShort() & 0xFFFF;
			bb.get();	// skip id
			int size = (bb.get() & 0xFF) * 2;
			short checkSum = bb.getShort();
			
			if (head == 0xABCD) {
				byte[] buf = Arrays.copyOf(t, size + 6);
				if ((in.read(buf, 6, size) == size) /*&& (checkSum(buf, 6, size) == checkSum)*/)
					return ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN);
			}

			in.reset();		// return to the remembered position
			in.read();		// skip byte
		}

	}

	@Override
	public int getId(ByteBuffer packet) {
		return (int)packet.get(2) & 0xFF;
	}
	
	/*
	 * Telematika checksum
	 */
    private short checkSum(byte[] data, int ofs, int size) {
		short result = (short)0xABCD;
		ByteBuffer bb = ByteBuffer.wrap(data, ofs, size).order(ByteOrder.LITTLE_ENDIAN);
	
		for (int i = 0; i < size; i += 2)
			result ^= bb.getShort();
	
        return result;
    }
	
	
}
